package com.fa7.android.example.listafacil;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CategoriaDB {
	private final static String DB_NAME = "categoria_db";
	private final static int DB_VERSION = 1;
	public final static String TABLE_NAME = "categorias";
	private final static String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT)";
	
	private SQLHelper mSqlHelper;
	private Context mContext;
	private SQLiteDatabase mDb;
	
	public CategoriaDB(Context c) {
		mContext = c;
		mSqlHelper = new SQLHelper(mContext, TABLE_NAME, DB_VERSION, CREATE_TABLE);
		mDb = mSqlHelper.getWritableDatabase();
	}
	
	public long insert(Categoria cat) {
		ContentValues content = new ContentValues();
		content.put("name",  cat.getName());
		content.put("description", cat.getDescription());
		
		return mDb.insert(TABLE_NAME, null, content);
	}
	
	public void update(Categoria cat) {
		ContentValues content = new ContentValues();
		content.put("name",  cat.getName());
		content.put("description", cat.getDescription());
		mDb.update(TABLE_NAME, content, "id = ?", new String[] {  cat.getId().toString() });
	}
	
	public void delete(Categoria cat) {
		mDb.delete(TABLE_NAME, "id = ?", new String[] {  cat.getId().toString() });
	}
	
	public Categoria query(Integer id) {
		Cursor c = mDb.query(TABLE_NAME, null, "id = ?", new String[] { id.toString() }, null, null, null);
		
		if (c.moveToFirst()) {
			return new Categoria(c);
		}
		
		return null;
	}
	
	public List<Categoria> queryAll() {
		Cursor c = mDb.query(TABLE_NAME, null, null, null, null, null, null);
		
		List<Categoria> list = new ArrayList<Categoria>();
		while (c.moveToNext()) {
			list.add(new Categoria(c));
		}
		
		return list;
	}
	
	public Cursor queryAllCursor(){
		Cursor c = mDb.query(TABLE_NAME, null, null, null, null, null, null);
		return c;
	}
}